package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
@Topic(TopicConfig.TASK_SUPPLY_TOPIC)
public class SupplyTaskHandler implements MsgHandler {

    @Autowired
    private TaskService taskService;

    @Autowired
    private VMService vmService;

    @Override
    public void process(String jsonMsg) throws IOException {
        try {
            //反序列化
            var supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
            if (supplyContract == null) return;

            //查出关联的售货机
            var vmInfo = vmService.getVMInfo(supplyContract.getInnerCode());
            //查出工单最少的用户
            var userId = taskService.getLeastUser(vmInfo.getRegionId(), false);

            //创建工单
            var taskViewModel = new TaskViewModel();
            taskViewModel.setCreateType(0); //工单类型
            taskViewModel.setInnerCode(supplyContract.getInnerCode()); //设备编号
            taskViewModel.setUserId(userId); //任务执行人id
            taskViewModel.setProductType(VMSystem.TASK_TYPE_SUPPLY); //工单类型
            taskViewModel.setDesc("自动补货工单");

            //工单详情
            List<TaskDetailsViewModel> taskDetailsViewModels = supplyContract.getSupplyData()
                    .stream().map(c -> {
                        var taskDetailsViewModel = new TaskDetailsViewModel();
                        //货道编号
                        taskDetailsViewModel.setChannelCode(c.getChannelId());
                        //补货数量
                        taskDetailsViewModel.setExpectCapacity(c.getCapacity());
                        //商品id、名称、图片
                        taskDetailsViewModel.setSkuId(c.getSkuId());
                        taskDetailsViewModel.setSkuName(c.getSkuName());
                        taskDetailsViewModel.setSkuImage(c.getSkuImage());

                        return taskDetailsViewModel;
                    }).collect(Collectors.toList());

            taskViewModel.setDetails(taskDetailsViewModels);

            taskService.create(taskViewModel);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("创建自动补货工单出错" + e.getMessage());
        }
    }
}
